# -*- coding: utf-8 -*-
# @author: edgardeng
# @date:   2021-05-08
# @file:   [websocket] https://websockets.readthedocs.io/en/stable/

""" websocket 文件上传管理 """


import asyncio
import json
import websockets
from websockets.protocol import State

list_client = {}

fold = r'D:\workspace\hello-python\part05_netwrok\websocket'
tmp = r'D:\workspace\hello-python\part05_netwrok\websocket\tmp'

async def file_manager(websocket, path):
    """
    1 发送文件列表请求
    2 接收文件列表数据
    3 发送文件上传要求
    4 接收文件数据
    """
    ask = {'action': 'file_list', 'params': fold}
    try:
        while websocket.state != State.CLOSED:
            await websocket.send(json.dumps(ask))
            # print(websocket.state)
            message = await websocket.recv()  # result , data
            msg = json.loads(message)
            print('-'*20, 'recv')
            print(msg)
            file_list = msg.get('data')
            ask = {'action': 'file_data', 'params': fold + '\\' + file_list[0].get('name')}
            await websocket.send(json.dumps(ask))
            file_data = await websocket.recv()
            print(type(file_data))
            # 打开一个新文件，以wb模式打开
            with open(tmp + '\\' + file_list[0].get('name'), 'wb') as file:
                file.write(file_data)

            break
    except websockets.exceptions.ConnectionClosedOK as e:
        print('close')
        print(e)

    await websocket.close()


async def broadcast_msg(id, msg, exclude):
    reply = '[Client: %s] said: %s' % (id, msg)

    for key in list_client:
        if key != exclude:
            client = list_client[key]
            if client.state == State.CLOSED:
                continue
            await client.send(reply)


if __name__ == '__main__':
    start_server = websockets.serve(file_manager, "localhost", 8765)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
